<template>
  <div>
    <el-page-header title="课程管理" @back="router.back()">
      <template #content>
        <span class="text-large font-600 mr-3">修改课程</span>
      </template>
    </el-page-header>

    <el-form ref="courseFormRef" :model="courseForm" :rules="courseFormRules" label-width="80px" class="demo-ruleForm" status-icon v-loading="loading">
      <el-row>
        <el-col :span="6">
          <el-form-item label="课程编号" prop="courseid">
            <el-input v-model="courseForm.courseid" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="课程名称" prop="coursename">
            <el-input v-model="courseForm.coursename" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="授课教师" prop="courseteacher">
            <el-select v-model="courseForm.courseteacher" class="m-2" placeholder="Select" style="width: 100%" filterable>
              <el-option v-for="item in teacherOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="9">
          <el-form-item label="专业" prop="major">
            <el-input v-model="courseForm.major" />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="班级" prop="classes">
            <el-input v-model.number="courseForm.classes" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="学期" prop="term">
            <el-select v-model="courseForm.term" class="m-2" placeholder="Select" style="width: 100%" filterable>
              <el-option v-for="item in termOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="学分" prop="credit">
            <el-input v-model.number="courseForm.credit" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="成绩类型" prop="type">
            <el-select v-model="courseForm.type" class="m-2" placeholder="Select">
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="成绩系数" prop="ratio" v-if="courseForm.type === 1">
        <el-button @click="handleSetRatio">点击设置</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm()">提交修改</el-button>
      </el-form-item>
    </el-form>

    <!-- 成绩系数对话框 -->
    <el-dialog v-model="dialogVisible" title="成绩系数设置" width="50%">
      <el-alert style="margin-bottom: 20px; margin-top: -30px" title="各个系数比值之和应为10" type="info" :closable="false" show-icon />
      <el-form>
        <el-row>
          <el-col :span="12">
            <el-form-item label="平时成绩">
              <el-input-number v-model="num1" :min="0" :max="10" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实验成绩">
              <el-input-number v-model="num2" :min="0" :max="10" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="期中成绩">
              <el-input-number v-model="num3" :min="0" :max="10" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="期末成绩">
              <el-input-number v-model="num4" :min="0" :max="10" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button style="margin-left: 618px" size="large" type="primary" @click="submitRatio()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import axios from 'axios'
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
const router = useRouter()
const route = useRoute()
const loading = ref(true)
const dialogVisible = ref(false)
const courseFormRef = ref()
const courseForm = reactive({
  courseid: null,
  coursename: '',
  courseteacher: null,
  major: '',
  classes: null,
  term: null,
  credit: null,
  type: null,
  ratio: ''
})
const courseFormRules = reactive({
  courseid: [{ required: true, message: '请输入课程编号', trigger: 'blur' }],
  coursename: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  courseteacher: [{ required: true, message: '请选择任课老师', trigger: 'blur' }],
  major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
  classes: [
    { required: true, message: '请输入班级', trigger: 'blur' },
    { type: 'number', message: '班级应是数字' }
  ],
  term: [{ required: true, message: '请选择学期', trigger: 'blur' }],
  credit: [
    { required: true, message: '请输入学分', trigger: 'blur' },
    { type: 'number', message: '学分应是数字' }
  ],
  type: [{ required: true, message: '请选择成绩类型', trigger: 'blur' }]
})
const teacherOptions = reactive([]) // 响应式
const termOptions = [
  { label: '2023-2024学年第1学期', value: 20231 },
  { label: '2023-2024学年第2学期', value: 20232 }
]
const typeOptions = [
  { label: '百分制', value: 1 },
  { label: '等级划分制', value: 2 }
]
const num1 = ref(0) //平时成绩
const num2 = ref(0) //实验成绩
const num3 = ref(0) //期中成绩
const num4 = ref(0) //期末成绩

let Oldcourseteacher = ''

onMounted(async () => {
  // console.log(route.params.id)
  // 获取课程表数据
  const res1 = await axios.get(`/api/course/list/${route.params.id}`)
  Object.assign(courseForm, res1.data.data[0])
  // 教师工号改为名字
  const res2 = await axios.get('/api/user/getteacherlist')
  res2.data.data.forEach((item) =>
    teacherOptions.push({
      label: item.name,
      value: item.username
    })
  )
  loading.value = false

  // 记录一下旧的任课教师
  Oldcourseteacher = res1.data.data[0].courseteacher
  // console.log(Oldcourseteacher)
  // console.log(courseForm)
})

const handleSetRatio = () => {
  if (courseForm.ratio) {
    let arr = courseForm.ratio.split(',')
    // console.log(arr)
    num1.value = Number(arr[0])
    num2.value = Number(arr[1])
    num3.value = Number(arr[2])
    num4.value = Number(arr[3])
  }
  dialogVisible.value = true
}
const submitRatio = () => {
  let arr = []
  arr.push(num1.value ? num1.value : 0)
  arr.push(num2.value ? num2.value : 0)
  arr.push(num3.value ? num3.value : 0)
  arr.push(num4.value ? num4.value : 0)
  // console.log(_.sum(arr))
  if (_.sum(arr) === 10) {
    // console.log(arr.join(','))
    courseForm.ratio = arr.join(',')
    // console.log(courseForm)
    ElMessage.success('设置成功！')
    dialogVisible.value = false
  } else {
    ElMessage.error('请设置正确的成绩系数！')
  }
}
const submitForm = async () => {
  if (courseForm.type === 2) {
    courseForm.ratio = '0,0,0,10'
  }
  // console.log(courseForm)
  await axios.put(`/api/course/list/${route.params.id}`, courseForm)
  // 任课老师发生改变
  if (courseForm.courseteacher !== Oldcourseteacher) {
    await handleTeacherCourse(courseForm.courseteacher) //给新老师加上新的任课信息
    await handleOldTeacherCourse(Oldcourseteacher) //给旧老师去掉该课程
  }

  ElMessage.success('修改成功！')
  router.push(`/course-manage/courselist`)
}
// 处理教师授课信息
const handleTeacherCourse = async (username) => {
  // 1先查询当前老师的任课信息（返回的是字符串）
  let arr = []
  const res = await axios.get(`/api/teacher/getcourse/${username}`)
  // 2查看任课信息是否为空 如空，直接插入；不为空，进一步处理
  if (res.data.data[0].mycourses) {
    arr = res.data.data[0].mycourses.split(',') //将取得的字符串转为数组
    arr.push(String(courseForm.courseid)) //尾插本次的课程编号
    let mycourses = arr.join(',') //数组转为字符串
    await axios.post(`/api/teacher/postcourse/${username}`, { mycourses })
  } else {
    await axios.post(`/api/teacher/postcourse/${username}`, { mycourses: String(courseForm.courseid) })
  }
}
const handleOldTeacherCourse = async (username) => {
  // 1先查询当前老师的任课信息（返回的是字符串）
  let arr = []
  const res = await axios.get(`/api/teacher/getcourse/${username}`)
  // 2查找到该项后删除 重新插入
  arr = res.data.data[0].mycourses.split(',') //将取得的字符串转为数组
  arr.forEach((item, index) => {
    if (Number(item) === courseForm.courseid) {
      arr.splice(index, 1) //从index开始删除 1项
    }
  })
  const newMycourses = arr.join(',') //数组转为字符串
  // console.log(arr)
  // console.log(newMycourses)
  await axios.post(`/api/teacher/postcourse/${username}`, { mycourses: newMycourses })
}
</script>

<style lang="scss" scoped>
.demo-ruleForm {
  margin-top: 50px;
}
</style>
